<?php
namespace app\index\controller;
use app\index\controller\Base;
use app\index\model\Set;
use app\index\model\Good;
use app\index\model\Coupon;
use app\index\model\Instance;
use app\index\model\User;
use app\index\model\Log;
use think\Db;
use think\Request;

class Qn extends Base
{
    private $shop_id='';
    public function __construct(){
    	$this->shop_id=Request::instance()->param('shop_id');
    }
    public function getSet(){
    	//$data=Set::get(['shop_id'=>$this->shop_id]);
        $data=Db::name('set')->where('shop_id',$this->shop_id)->find();
        $good=Good::all(['shop_id'=>$this->shop_id]);
        $coupon=Coupon::get(['shop_id'=>$this->shop_id]);
        $data['good']=$good;
        $data['coupon']=$coupon;
    	$this->success($data);
    }
    public function getGood(){
    	$data=Good::all(['shop_id'=>$this->shop_id]);
    	$this->success($data);
    }
    public function getCoupon(){
    	$data=Coupon::get(['shop_id'=>$this->shop_id]);
    	$this->success($data);
    }
    public function getInstance(){
    	$data=Instance::get(['shop_id'=>$this->shop_id]);
    	$this->success($data);
    }
    public function writeSet(){
    	$data=Request::instance()->param();
    	if($this->check('set')){
    		$set=new Set;
    		$set->allowField(true)->save($data,['shop_id'=>$this->shop_id]);
    	}else{
    		$set=new Set($data);
    		$set->allowField(true)->save();
    	}
    	$this->success($data);
    }
    public function writeGood(){
        Db::name('good')->where('shop_id',$this->shop_id)->delete();
    	$goodList=Request::instance()->param('goodList');
        //$goodList=stripslashes($goodList);
        $goodList=json_decode($goodList,true);
        $goodList2=[];
        foreach($goodList as $k=>$v){
            $v2=json_decode($v,true);
            $goodList2[]=$v2;
        }
    	$good=new Good;
    	$good->allowField(true)->saveAll($goodList2);
    	$this->success($goodList);
    }
    public function writeCoupon(){
    	$data=Request::instance()->param();
    	//Coupon::destroy(['shop_id'=>$this->shop_id]);
        if($this->check('coupon')){
            $coupon=new Coupon;
            $coupon->allowField(true)->save($data,['shop_id'=>$this->shop_id]);
            
        }else{
            $coupon=new Coupon($data);
            $coupon->allowField(true)->save();
        }
    	$this->success($data);
    }
    public function writeInstance(){
    	$data=Request::instance()->param();
        if($this->check('instance')){
            $instance=new Instance;
            $instance->allowField(true)->save($data,['shop_id'=>$this->shop_id]);
        }else{
            $instance=new Instance($data);
            $instance->allowField(true)->save();
        }
    	
    	$this->success($data);
    }
     public function check($db)
    {
        $data=Db::name($db)->where(['shop_id'=>$this->shop_id])->find();
        if(count($data)==0){
            return false;
        }else{return true;}

    }

}
